package com.chenfan.mcn.service.helper;

import com.chenfan.common.exception.BusinessException;
import com.chenfan.common.extension.context.UserContextHolder;
import com.chenfan.mcn.clients.privilege.DepartmentVO;
import com.chenfan.mcn.clients.privilege.PrivilegeClient;
import com.chenfan.mcn.exception.McnErrorCode;
import com.chenfan.mcn.utils.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Map;
import java.util.Objects;

/**
 * @author wulg
 * @date 2024/3/22
 */
@Service
public class CommonHelper {

    @Autowired
    private PrivilegeClient privilegeClient;

    /**
     * 校验执行人权限
     * @param excutorId
     * @param skip
     * @return
     */
    public DepartmentVO verifyExcutorAuth(Long excutorId, boolean skip) {
        if(Objects.isNull(excutorId)) {
            return null;
        }
        Long userId = UserContextHolder.getUserId();
        if(!skip && excutorId.equals(userId)) {
            return null;
        }
        Map<Long, DepartmentVO> departmentVoMap = privilegeClient.getDepartmentHeadByUserIds(Arrays.asList(excutorId)).getObj();
        if(CommonUtil.containsKey(departmentVoMap, excutorId)) {
            DepartmentVO departmentVO = departmentVoMap.get(excutorId);
            if(Objects.nonNull(departmentVO) && userId.equals(departmentVO.getDepartmentHeadId())) {
                return departmentVO;
            }
        }
        throw new BusinessException(skip ? McnErrorCode.EXCUTION_LEADER_NO_AUTH : McnErrorCode.EXCUTION_NO_AUTH);
    }
}
